package com.grm.sys.service.impl;

import com.grm.common.exception.BusinessException;
import com.grm.common.utils.*;
import com.grm.sys.mapper.SysUserMapper;
import com.grm.sys.model.SysUser;
import com.grm.sys.request.login.LoginRequest;
import com.grm.sys.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public String login(LoginRequest loginRequest) {
        SysUser sysUser = sysUserMapper.queryByUsername(loginRequest.getUsername());
        if (sysUser == null) {
            throw new BusinessException("用户不存在！");
        }
        if (!PasswordUtils.checkPassword(loginRequest.getPassword(), sysUser.getPassword())) {
            throw new BusinessException("密码错误！");
        }
        String token = jwtUtil.createToken(loginRequest.getUsername(), sysUser.getId());
        redisUtil.setExpire(String.format("token_%s", sysUser.getUsername()), token, 2L, TimeUnit.HOURS);
        return token;
    }
}
